package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.sdk.client.DyTtClient;
import com.dy.sdk.model.request.tt.TtAssetsCreateRequest;
import com.dy.sdk.model.response.tt.TtResponse;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.ads.pig.mapper.AdAssetsMapper;
import com.pig4cloud.pig.ads.service.*;
import com.pig4cloud.pig.api.dto.AdAssetsRes;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.entity.AdAssets;
import com.pig4cloud.pig.api.entity.TtAppManagement;
import com.pig4cloud.pig.api.vo.AdAssetsReq;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 广告资产表
 * @author  chenxiang
 * @version  2022-04-01 15:02:28
 * table: ad_assets
 */
@Log4j2
@Service("adAssetsService")
@RequiredArgsConstructor
public class AdAssetsServiceImpl extends ServiceImpl<AdAssetsMapper, AdAssets> implements AdAssetsService {

	private final AdAssetsMapper adAssetsMapper;
	private final TtAppManagementService ttAppManagementService;
	private final TtAccesstokenService ttAccesstokenService;
	private final AdvService advService;
	private final AdAccountService adAccountService;

	/**
	 * 分页列表
	 * @param req
	 * @return
	 */
	@Override
	public R getPage(AdAssetsReq req){
		List<String> adList = Lists.newArrayList();
		//当前登录人所关联角色对应的投放人集合
		List<String> throwUserList = advService.getThrowUserList();
		// throwUserList == null 表示 为管理员或关联的角色关联了全部投放人
		if (!CollectionUtils.isEmpty(throwUserList)) {
			adList = adAccountService.list(Wrappers.<AdAccount>query().lambda()
					.and(wrapper -> wrapper.in(AdAccount::getThrowUser, throwUserList)))
					.stream().map(AdAccount::getAdvertiserId).collect(Collectors.toList());
		}
		req.setAdList(adList);
		IPage<AdAssetsRes> iPage = adAssetsMapper.selectAdAssets(req);
		return R.ok(iPage);
	}
	/**
	 * 新建资产
	 * @param req
	 * @return
	 */
	@Override
	public R addAssets(AdAssetsReq req){
		try {
			String advertiserId = req.getAdvertiserId();
			String appCloudId = req.getAppCloudId();
			TtAppManagement ttAppManagement = ttAppManagementService.getOne(Wrappers.<TtAppManagement>lambdaQuery().eq(TtAppManagement::getAdvertiserId, advertiserId).eq(TtAppManagement::getAppCloudId,appCloudId).eq(TtAppManagement::getIsDeleted, 0));
			if (Objects.isNull(ttAppManagement)){
				return R.failed("未获取到应用信息");
			}
			AdAssets adAssets = new AdAssets();
			adAssets.setAdvertiserId(ttAppManagement.getAdvertiserId());
			adAssets.setAssetType(StringUtils.isBlank(req.getAssetType()) ? "APP" : req.getAssetType());
			adAssets.setPackageId(ttAppManagement.getPackageId());
			adAssets.setPackageName(ttAppManagement.getPackageName());
			adAssets.setAppCloudId(ttAppManagement.getAppCloudId());
			adAssets.setAppName(ttAppManagement.getAppName());
			adAssets.setAppType(StringUtils.isBlank(req.getAppType()) ? "Android" : req.getAppType());
			adAssets.setDownloadUrl(ttAppManagement.getDownloadUrl());
			adAssets.setAssetName(ttAppManagement.getAppName());
			adAssets.setSoucreStatus(1);
			adAssets.setCreateId(SecurityUtils.getUser().getId().longValue());
			adAssets.setUpdateId(SecurityUtils.getUser().getId().longValue());
			// 调用头条创建资产
			R result = createTtAssets(adAssets);
			if (0 == result.getCode()){
				Long assetId = (Long) result.getData();
				adAssets.setAssetId(assetId);
				this.save(adAssets);
				return R.ok();
			}
			return R.failed(result.getMsg());
		} catch (Exception e) {
			log.info(">>>>>>新建资产异常:{}",e.getMessage());
			return R.failed("新建资产异常:"+e.getMessage());
		}
	}
	/**
	 * 调用头条 - 创建资产
	 * @param adAssets
	 * @return
	 */
	public R createTtAssets(AdAssets adAssets){
		try {
			String accessToken = ttAccesstokenService.fetchAccesstoken(adAssets.getAdvertiserId());
			DyTtClient ttClient = new DyTtClient("");
			TtAssetsCreateRequest assetsCreateRequest = new TtAssetsCreateRequest();
			assetsCreateRequest.setAdvertiser_id(Long.valueOf(adAssets.getAdvertiserId()));
			assetsCreateRequest.setAsset_type(adAssets.getAssetType());
			Map<String, Object> app_asset = new HashMap<>();
			app_asset.put("name",adAssets.getAssetName());
			app_asset.put("package_name",adAssets.getPackageName());
			app_asset.put("download_url",adAssets.getDownloadUrl());
			app_asset.put("app_id",Long.valueOf(adAssets.getAppCloudId()));
			app_asset.put("package_id",adAssets.getPackageId());
			app_asset.put("app_type",adAssets.getAppType());
			assetsCreateRequest.setApp_asset(app_asset);
			log.info(">>>>>>调用头条创建资产params：{}",JSON.toJSONString(assetsCreateRequest));
			String result = ttClient.call4Post(assetsCreateRequest, accessToken);
			log.info(">>>>>>调用头条创建资产result：{}",result);
			TtResponse response = JSON.parseObject(result, TtResponse.class);
			if ("0".equals(response.getCode())){
				JSONObject jsonObject = response.getData();
				Long assetId = jsonObject.getLong("asset_id");
				return R.ok(assetId);
			}else{
				log.error(">>>>>>调用头条创建资产异常：{}",response.getMessage());
				return R.failed(response.getMessage());
			}
		} catch (Exception e) {
			log.error(">>>>>>调用头条创建资产异常：{}",e.getMessage());
		}
		return R.failed();
	}
}